#!/usr/bin/php5
<?PHP
        /*      This backup plugin handles backing up of imap email
                services as part of the Saasy-Backup Startup Weekend Phoenix
                Orig Date: 10-18-2008
		Written By: Brian Roy

		Dependencies: php5, php-imap, offlineimap, python, python-support
                
                Usage: ./imap-mail-backup.php pword=<imap password> username=<imap username> outfile=<backup file gzip'd> workdir=<where work files are or are created> service=<imap service (e.g., GMAIL)> type=<run or query - query only returns # records and size>

        */
	
	// Constants
	
	define("USERNAME", "username");
	define("PASSWORD", "pword");
	define("SERVICE", "service");
	define("OUTFILE", "outfile");
	define("WORKDIR", "workdir");
	define("TYPE", "type");
	define("SERVICEGMAIL", "GMAIL");
	define("GMAILCONFTEMPLATE", "gmail-template.conf");	
	define("PATHTOOFFLINEIMAP", "/usr/bin/offlineimap");
	define("TYPEQUERY", "query");
	define("TYPERUN", "run");
	
	header("content-type: text/xml");
	echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
	
	// Functions
	
	function getGMailMailboxMeta($username, $password) {
		//echo "Username: ".$username."\nPwd: ".$password."\n";		
		$mbox = imap_open("{imap.gmail.com:993/imap/ssl/novalidate-cert}[Gmail]/All Mail", trim($username), trim($password));

		if($mbox) {
	
	        $check = imap_mailboxmsginfo($mbox);
	
	        if ($check) {
	                $strPartXML = "<mailsize>\n<msgcount>".$check->Nmsgs."</msgcoung>\n<size>".$check->Size."</size>\n</mailsize>\n";
	
	                echo $strPartXML;
	                return true;
	        } else {
	                echo "<xml>\n<result>404</result><error>Failed to query mailbox for number of messages and size. ".imap_last_error()."</error>\n</xml>\n";
	                return false;
	        }
	
	
	        imap_close($mbox);
		} else {
			
			echo "<xml>\n<result>403</result><error>Failed to query mailbox for number of messages and size. ".imap_last_error()."</error>\n</xml>\n";
			return false;		
		}
		
	}

        // Absorb Command Line Args
        $strUsername = false;
        $strPwd = false;
        $strSvc = false;
        //print_r($argv);
        if(count($argv) == 7) {
        		$blnIsValid = false;
                for($i=1; $i<(count($argv)); ++$i) {
                		//echo "Processing: ".$argv[$i]."\n";
                        $aryVals = explode("=", $argv[$i]);
                        if($aryVals[0] == USERNAME) {
                        	$strUsername = $aryVals[1];
                    	    $blnValid = true;
                        }
                        if($aryVals[0] == PASSWORD) {
                       		$strPwd = $aryVals[1];
                       		$blnValid = true;
                        }
                        if($aryVals[0] == SERVICE) {
                        	$strSvc = $aryVals[1];
                        	$blnValid = true;
                        }
                        if($aryVals[0] == OUTFILE) {
                        	$strOutfile = $aryVals[1];
                        	$blnValid = true;
                        }
                        if($aryVals[0] == WORKDIR) {
                        	$strWorkDir = $aryVals[1];
                        	$blnValid = true;
                        }
                        if($aryVals[0] == TYPE) {
                        	$strType = $aryVals[1];
                        	$blnValid = true;
                        }
                }
                if(!$blnValid) {
                	// A specific item was not valid.
                	//echo "part one: ".$aryVals[0]."\npart two: ".$aryVals[1]."\n";
                	echo "<xml>\n<result>401</result><error>Missing input(s) - Service, Username and Password are all required. idx= ".$i." ".$argv[$i]."</error>\n</xml>\n";
              		exit;
                } 
                if(!$strSvc || !$strUsername || !$strPwd || !$strOutfile || !$strWorkDir || !$strType) {
                	// Missing an element
                	//echo "Workdir = ".$strWorkDir."\nOutfile = ".$strOutFile."\nService = ".$strSvc."\nUsername = ".$strUsername."\nPassword = ".$strPwd."\n";
                	echo "<xml>\n<result>402</result><error>Missing input(s) - Service, Username and Password are all required.</error>\n</xml>\n";
                	exit;
                }
                
                // OK -- we got all of the information required. 
                
                //Begin XML Output
                if($strSvc == SERVICEGMAIL) {
                	echo "<xml>\n";
					if(getGMailMailboxMeta($strUsername, $strPwd)) {
                	//if(true) {
                		// We got size and message count - continue.	
                		
                		if($strType == TYPERUN) {
                		
	                		// Create the conf file for this backup.
	                		$strTemplate = file_get_contents($strWorkDir."/".GMAILCONFTEMPLATE);
	                		if($strTemplate) {
	                			$strNewConf = str_replace("<username>", $strUsername, $strTemplate);
	                			$strNewConf = str_replace("<password>", $strPwd, $strNewConf);
	                			$strNewConf = str_replace("<workdir>", $strWorkDir, $strNewConf);
	                		
	                			$strConfName = $strWorkDir."/".$strUsername.".conf";
	                		
	                			$fpConf = fopen($strConfName, 'w');
	                			if($fpConf) {	
	                				fwrite($fpConf, $strNewConf);
	                				
	                				fclose($fpConf);
	                				
	                				// New conf file written... run offlineimap.
	                				$strCmd = "mkdir ".$strWorkDir."/".$strUsername;
							exec($strCmd);	
							$strCmd = PATHTOOFFLINEIMAP." -c ".$strConfName;
	                				echo "<offlineimap-output>";
	                				exec($strCmd);
	                				echo "</offlineimap-output>\n";
	                				// Now the imap backup should be complete and have created Maildir...
	                				// Just need to tar it up into a gzip in the specified outfile.
	                				
	                				$strCmd = "tar -cvf ".$strOutfile." ".$strWorkDir."/".$strUsername;
	                				echo "<tar-output>";
	                				exec($strCmd);
	                				echo "</tar-output>\n";
	                				
	                				// done... return the info to the orchestator...
	                				
	                				echo "<result>200</result>\n</xml>\n";
                				
	                			} else {
	                				// couldn't create conf file... bad work dir?
	                				echo "<result>405</result><error>Could not create a file in workdir.</error>\n</xml>\n";
	                			}
	                		
	                		} else {
	                			// couldn't open config file template... bad work dir?
	                			 echo "<result>406</result><error>Could not open the conf temlate gmail-template.conf in the workdir.</error>\n</xml>\n";
	                			
	                		}
                		}
                		if($strType == TYPEQUERY) {
                			echo "<result>200</result>\n</xml>\n";
                		}
                	} else {
                		// There was an error getting message count and mailbox size... we are done
                	}
                	
                }

        } else {
                // We require all four elements - return xml error

                echo "<xml>\n<result>400</result><error>Missing input(s) - Service, Username and Password are all required.</error>\n</xml>\n";
        }




?>
